package com.why.blog.filter;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.why.blog.common.BusinessRuntimeException;
import com.why.blog.common.JwtTokenUtils;
import com.why.blog.common.ResponseCode;
import com.why.blog.entity.JwtUser;
import com.why.blog.entity.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private ThreadLocal<Integer> rememberMe = new ThreadLocal<>();
    @Autowired
    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager){
        this.authenticationManager = authenticationManager;
        super.setFilterProcessesUrl("/auth/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        //从输入流中获取登录信息
        try {
            LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
            //前台传rememberMe参数
            if(null !=loginUser.getRememberMe()){
                rememberMe.set(loginUser.getRememberMe());
            }else {
                rememberMe.set(0);
            }
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>())
            );
        }catch (IOException e){
            throw new BusinessRuntimeException(ResponseCode.LOGIN_NO_PASS,ResponseCode.LOGIN_NO_PASS.getMsg());
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        JwtUser uvo = (JwtUser)authResult.getPrincipal();
        boolean isRemember = rememberMe.get() == 1;
        String role = "";
        Collection<? extends GrantedAuthority> authorities = uvo.getAuthorities();
        //获取权限角色
        for (GrantedAuthority authority: authorities){
            role = authority.getAuthority();
        }
        String token = JwtTokenUtils.createToken(uvo.getUsername(),role,isRemember,uvo.getUserId());
        // 按照jwt的规定，最后请求的时候应该是 `Bearer token`
        response.setHeader("token",JwtTokenUtils.TOKEN_PREFIX+token);
        JwtUser user = new JwtUser();
        user.setUserId(uvo.getUserId());
        user.setUserName(uvo.getUsername());
        JSONObject json =new JSONObject();//将java对象转换为json对象
        json.put("status",ResponseCode.RESPONSE_SUCCESS.getCode());
        json.put("user",user);
        String str = json.toString();
        response.getWriter().write(str);
        response.getWriter().flush();
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.getWriter().write(ResponseCode.LOGIN_NO_PASS.getCode());
    }
}
